<template>
  <el-dialog :title="'机构配置3版'" :close-on-click-modal="false" :visible.sync="visible" width="950px" @close="clearDataList()" top="8vh">
    <!--<div style="margin: 0 0 10px 0;">-->
    <!--  <el-link icon="el-icon-plus" type="primary"  @click="openSelectFz" :underline="false">选择机构</el-link>-->
    <!--</div>-->
    <div style="height:65vh; overflow-y: auto">
      <div v-for="(a1,index1) in sourceData" class="boxsty mb10 w99">
        <div>
          <span class="fontweight blue">序号：{{ index1 + 1 }}</span>
          <span class="fontweight ml30 blue">奖金项：</span><span class="w200">{{a1.jjxName}}</span>
          <span class="fontweight blue ml30">奖金项Data：</span>{{a1.jjxDate}}
          <div style="float: right">
            <el-link icon="el-icon-plus" type="primary"  @click="openSelectFz(index1)" :underline="false">选择机构</el-link>
          </div>
        </div>
        <div v-for="(a2,index2)  in sourceDataSub[a1.jjxId]">
          <div style="margin: 10px 0 0 0">{{ index2 + 1 }} 分组名称：{{ a2.fzName }}
            <el-button type="primary" plain @click="btnAddItem($event,index1,index2)" class="ml10">+</el-button>
            <el-button type="danger" plain @click="btnDel($event,index1,index2)" class="ml10">删除分组</el-button>
            <!--<span style="color: #ff0000" class="ml10">{{a2.errMsg}}</span>-->
          </div>
          <div>
            <el-collapse v-model="index3" v-for="(a3,index3)  in sourceDataSub[a1.jjxId][index2].jjConfig" :key="index3">
              <el-collapse-item :name="index3">
                <template slot="title">
                  <div><span class="numTip" style="padding:5px 10px;">{{ index3 + 1 }}</span> {{ a2.fzName }}
                    <el-button type="danger" plain @click="btnDel3($event,index1,index2,index3)" class="ml10">-</el-button>
                    <span style="color: #ff0000" class="ml10">{{a3.errMsg}}</span>
                  </div>
                </template>
                <div class="mb10">
                  <el-row>
                    <el-col :span="2">奖金项：</el-col>
                    <el-col :span="10">
                      <el-select :clearable="true" v-model="a3.jjxId" placeholder="请选择" class="xiaLa" @change="elJjxChange($event,index1,index2,index3)">
                        <el-option v-for="(item,index) in jjxOptions " :key="index" :label="item.jjxMc" :value="item.id">
                        </el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="2">公式：</el-col>
                    <el-col :span="10">
                      <el-select v-model="a3.gsId" placeholder="请选择" clearable @change="elGsChange($event,index1,index2,index3)" class="xiaLa">
                        <el-option v-for="(item1,index) in gsData " :key="index" :label="item1.gsMc" :value="item1.id">
                        </el-option>
                      </el-select>
                    </el-col>
                  </el-row>
                </div>
                <div>
                  <el-row>
                    <el-col :span="2">金额：</el-col>
                    <el-col :span="10">
                      <el-input-number v-model="a3.jjJe" :precision="2" :step="1" :min="0" style="width:240px;"></el-input-number>
                    </el-col>
                    <el-col :span="2">日期：</el-col>
                    <el-col :span="10">
                      <el-date-picker v-model="a3.jjxDate" placeholder="日期" style="width:240px;" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                    </el-col>
                  </el-row>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>

      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit()" >确定</el-button>
      <el-button @click="clearDataList" type="primary" plain>取消</el-button>
    </span>
    <!--选择机构分组-->
    <Jgfzsz v-if="jgfzszVisible" ref="jgfzsz" @getChildValue="setJgfzStr"></Jgfzsz>
  </el-dialog>
</template>

<script>
import Jgfzsz from './jiangjinjgpzfz3'
import {getJiangJinBm} from '@/api/admin/dept'
import {getJjDeptJjgtoPrant} from '@/api/admin/sysformula'
import {getJjDeptJjx} from '@/api/jiangjin/jiangjinjjxxxb'

export default {
  name: "jiangjinjgpzy3",
  components:{
    Jgfzsz
  },
  data(){
    return{
      visible: false,
      jgfzszVisible: false,
      deptId: '',
      deptName: '',
      //公式List
      gsData: [],
      //奖金项
      jjxOptions: [],
      //数据配置源主
      sourceData:[],
      //数据配置源子
      sourceDataSub:{},

      //主index
      sourceDataIndex: -1,
      activeName: [],

    }
  },
  methods:{
    //获取奖金管理人机构
    getJiangJinJg() {

      getJiangJinBm().then(res => {
        if (res.data.data != null && res.data.data.length > 0) {
          this.deptId = res.data.data[0].deptId;
          this.deptName = res.data.data[0].name;
          this.refresh();
          this.getBaseData();


        } else {
          this.$notify.closeAll();
          //this.$notify.error("没有相关负责部门")
          //this.deptName = "无相关负责部门";
        }
      });
    },
    //取得基本数据
    getBaseData(){
      //取得公式数组
      getJjDeptJjgtoPrant({id: this.deptId,gsType:'奖金算法',gsFl:'部门'}).then(res => {
        this.gsData = res.data.data;
        ////console.log(this.gsData);
      })

      //取得奖金项
      getJjDeptJjx(this.deptId).then(res =>{
        const xData = res.data.data;
        this.jjxOptions = [];
        this.jjxOptions = xData;
        ////console.log(xData);
        // value: item.id,
        //   label: item.jjxMc})
      })
    },
    //取得奖金项名称
    getJJxName(key){
      let lResult = "";
      this.jjxOptions.find(u =>{
        if(u.id === key){
          lResult = u.jjxMc;
        }
      })
      return lResult;
    },
    //取得公式名称
    getGsMc(key){
      let lResult = "";
      this.gsData.find(u =>{
        if(u.id === key){
          lResult = u.gsMc;
        }
      })
      return lResult;
    },
    init(){
      this.visible = true;
      this.getJiangJinJg();
    },
    refresh(){
      //1.主取得
      this.sourceData = [];
      this.sourceData.push({
        jjxId:13,
        jjxName:"测试三",
        jjxDate:"jjxDate_1_A"
      })
      this.sourceData.push({
        jjxId:15,
        jjxName:"测试五",
        jjxDate:"jjxDate_2_B"
      })
      // this.sourceData.push({
      //   jjxId:20,
      //   jjxName:"Test",
      //   jjxDate:"jjxDate_3_C"
      // })
      // this.sourceData.push({
      //   jjxId:21,
      //   jjxName:"吉林奖金",
      //   jjxDate:"jjxDate_4_D"
      // })


      //2.生成子
      this.sourceDataSub = {};
      for(let i=0;i<this.sourceData.length;i++){
        this.$set(this.sourceDataSub,this.sourceData[i]["jjxId"],[]);
      }

    },
    //设置是否禁选
    getSelectJg(){
      let lResult = [];
      const lId = this.sourceData[this.sourceDataIndex].jjxId;

      if(this.sourceDataSub[lId] !== undefined){
        for(let i=0;i<this.sourceDataSub[lId].length;i++){
          lResult.push(this.sourceDataSub[lId][i].fzId);
        }
      }

      return lResult.join(',');
    },
    //选择分组
    openSelectFz(index1){
      this.sourceDataIndex = -1;
      this.sourceDataIndex = index1;
      this.jgfzszVisible = true

      this.$nextTick(() => {
        this.$refs.jgfzsz.init(this.deptId,this.getSelectJg());
      })
    },
    clearDataList(){
      // this.sourceData = [];
      this.sourceDataSub = {};
      this.sourceDataIndex = -1;

      this.visible =false;
    },

    setError1(){
      let sStr = [];
      sStr = Object.keys(this.sourceDataSub);
      ////console.log(sStr);

      for(let i=0;i<sStr.length;i++){
        for(let j=0;j<this.sourceDataSub[sStr[i]].length;j++){
          for(let k=0;k<this.sourceDataSub[sStr[i]][j]["jjConfig"].length;k++){
            this.sourceDataSub[sStr[i]][j]["jjConfig"][k].errMsg = "";
            if(this.sourceDataSub[sStr[i]][j]["jjConfig"][k].jjxId === ""){
              this.sourceDataSub[sStr[i]][j]["jjConfig"][k].errMsg= "奖金项未选择";
              continue;
            }
            if(this.sourceDataSub[sStr[i]][j]["jjConfig"][k].gsId === ""){
              this.sourceDataSub[sStr[i]][j]["jjConfig"][k].errMsg= "公式未选择";
              continue;
            }
            if(this.sourceDataSub[sStr[i]][j]["jjConfig"][k].jjxDate === "" ||
              this.sourceDataSub[sStr[i]][j]["jjConfig"][k].jjxDate == null){
              this.sourceDataSub[sStr[i]][j]["jjConfig"][k].errMsg= "日期未选择";
              continue;
            }
          }
        }
      }
    },

    //取得比较数据1
    getComparesIndex(l1){
      let sStr = [];
      for(let i=0;i<l1;i++){
        // sStr.push(this.sourceData[i].jjxId+'_'+this.sourceData[i].jjxName)
        sStr.push(this.sourceData[i].jjxId)
      }
      return sStr;
      // return sStr.join(',');
    },
    //取得比较数据2
    getComparesJjxId(str){
      let l1 = [];
      let l2 = [];

      for(let i=0;i<str.length;i++){
        for(let j=0;j<this.sourceDataSub[str[i]].length;j++){
          for(let k=0;k<this.sourceDataSub[str[i]][j]["jjConfig"].length;k++){
            l1.push(this.sourceDataSub[str[i]][j]["jjConfig"][k].jjxId)
          }
        }
      }

      //去重
      l2 = [...new Set(l1)];
      return l2;
    },

    setError2(){
      if(this.sourceData.length < 2){
        return;
      }

      // 0 1
      // 0 1 2
      // 0 1 2 3

      // 3
      // 15测试五|13_测试三
      // 20Test|13_测试三,15_测试五
      // 21吉林奖金|13_测试三,15_测试五,20_Test

      // 1.比较
      let l1 = this.sourceData.length - 1;
      let strComparesn = [];
      let llId = '';
      let swich = false;


      for(let a=1;a<=l1;a++){
        ////console.log(this.sourceData[a].jjxId + this.sourceData[a].jjxName +'|'+this.getComparesIndex(a));

        strComparesn = [];
        llId = '';
        if(swich) break;

        llId = this.sourceData[a].jjxId;
        strComparesn = this.getComparesJjxId(this.getComparesIndex(a));

        // 调试用
        ////console.log( this.sourceData[a].jjxName +' >>> '+strComparesn)

        for(let b=0;b<this.sourceDataSub[llId].length;b++){
          if(swich) break;
          for(let c=0;c<this.sourceDataSub[llId][b]["jjConfig"].length;c++){
            this.sourceDataSub[llId][b]["jjConfig"][c].errMsg = "";

            if(strComparesn.indexOf(this.sourceDataSub[llId][b]["jjConfig"][c].jjxId) > -1){
              this.sourceDataSub[llId][b]["jjConfig"][c].errMsg = "【"+this.sourceDataSub[llId][b]["jjConfig"][c].jjxName+"】已存在于";
              this.sourceDataSub[llId][b]["jjConfig"][c].errMsg += this.showMessages(this.sourceDataSub[llId][b]["jjConfig"][c].jjxId);
              swich = true;
              break;
            }
          }
        }
      }


    },
    //最后详细说明
    showMessages(jjxId){
      let lResult = "";
      let bSwich = false;
      let lId = "";

      for(let i=0;i<this.sourceData.length;i++){
        lId = "";
        lId = this.sourceData[i].jjxId;
        if(bSwich) break;
        for(let j=0;j<this.sourceDataSub[lId].length;j++){
          if(bSwich) break;
          for(let k=0;k<this.sourceDataSub[lId][j]["jjConfig"].length;k++){
            if(this.sourceDataSub[lId][j]["jjConfig"][k].jjxId === jjxId){
              lResult = "序号："+ (i+1) +"【"+ this.sourceData[i].jjxName +"】"
              lResult += "_" + (j+1) + "【"+ this.sourceDataSub[lId][j].fzName +"】";
              lResult += "_"+(k+1)+"中";
              bSwich = true;
              break;
            }
          }

        }
      }
      return lResult;
    },
    setError3(){
      if(this.sourceData.length < 2){
        return;
      }

      // 1.定位比较得行
      let iCompareIndex = this.sourceData.length - 1;
      let strCompares = [];
      let strComparesn = [];
      let lId = 0;

      // 2.取得比较的数据
      for(let i=0;i<iCompareIndex;i++){
        lId = this.sourceData[i].jjxId;
        for(let j=0;j<this.sourceDataSub[lId].length;j++){
          strCompares.push(this.sourceDataSub[lId][j].jjxId);
        }
        lId = 0;
      }

      //去重
      strComparesn = [...new Set(strCompares)]


      ////console.log(strCompares)
      ////console.log(strComparesn)
      ////console.log('----')

      // 3.比较
      let llId = this.sourceData[iCompareIndex].jjxId

      for(let b=0;b<this.sourceDataSub[llId].length;b++){
        this.sourceDataSub[llId][b].errMsg = "";
        if(strComparesn.indexOf(this.sourceDataSub[llId][b].jjxId) > -1){
          this.sourceDataSub[llId][b].errMsg = "奖金项Id"+this.sourceDataSub[llId][b].jjxId+"重复";
          break;
        }
      }

      // 0 1
      // 0 1 2
      // 0 1 2 3

    },
    //错误提示
    submitError(){
      let lErr = false;
      let sStr = [];
      sStr = Object.keys(this.sourceDataSub);

      for(let i=0;i<sStr.length;i++){
        if(lErr) break;
        for(let j=0;j<this.sourceDataSub[sStr[i]].length;j++){
          lErr = this.submitErrorInner(this.sourceDataSub[sStr[i]][j]);
          if(lErr) break;
        }
      }
      return lErr;
    },
    //不修改原验证逻辑，添加
    submitErrorInner(sourceDataSub3){
      for(let k=0;k<sourceDataSub3["jjConfig"].length;k++){
        if(sourceDataSub3["jjConfig"][k].errMsg !==""){
          return true;
        }
      }
      return false;
    },

    dataFormSubmit() {

      this.setError1();
      if(this.submitError()){
        return;
      }

      this.setError2();
      if(this.submitError()){
        return;
      }

     //console.log('----')
     //console.log(this.sourceData)
     //console.log(this.sourceDataSub);
     //console.log('----')

    },
    btnDel(value,indexD,indexX){
      this.sourceDataSub[this.sourceData[indexD].jjxId].splice(indexX,1);
    },
    btnDel3(e,indexD,indexX,index3){
      e.stopPropagation();
      this.sourceDataSub[this.sourceData[indexD].jjxId][indexX].jjConfig.splice(index3,1);
    },
    elJjxChange(value,indexD,indexX,index3){
      const lId = this.sourceData[indexD].jjxId;
      this.$set(this.sourceDataSub[lId][indexX]["jjConfig"][index3],"jjxName",
        this.getJJxName(this.sourceDataSub[lId][indexX]["jjConfig"][index3].jjxId));
    },
    elGsChange(value,indexD,indexX,index3){
      const lId = this.sourceData[indexD].jjxId;
      this.$set(this.sourceDataSub[lId][indexX]["jjConfig"][index3],"gsName",
        this.getGsMc(this.sourceDataSub[lId][indexX]["jjConfig"][index3].gsId));
    },
    //加3级菜单
    btnAddItem(value,indexD,indexX){
      // this.sourceDataSub[this.sourceData[indexD].jjxId].splice(indexX,1);
      let lId = 0;
      lId = this.sourceData[indexD].jjxId;

      this.sourceDataSub[lId][indexX].jjConfig.push({
          gsId:'',
          gsName:"",
          jjJe:0,
          jjxId: lId,
          jjxName: this.getJJxName(lId),
          jjxDate:"",
          errMsg:''
      })

    },
    //设置
    setJgfzStr(obj){
      ////console.log(obj);

      let lId = 0;
      lId = this.sourceData[this.sourceDataIndex].jjxId;

      let sStr = [];
      sStr = Object.keys(this.sourceDataSub);

      // for(let j=0;j<obj.length;j++){
      //   // obj[j].id  obj[j].jgFzName
      //   this.sourceDataSub[sStr[i]].push({
      //     fzId:obj[j].id,
      //     fzName:obj[j].jgFzName,
      //     gsId:'',
      //     gsName:"",
      //     jjJe:0,
      //     jjxId: lId,
      //     jjxName: this.getJJxName(lId),
      //     jjxDate:"",
      //     errMsg:''
      //   })
      // }


      for(let i=0;i<sStr.length;i++)
      {
        if(sStr[i] == lId){
          for(let j=0;j<obj.length;j++){
            // obj[j].id  obj[j].jgFzName
            this.sourceDataSub[sStr[i]].push({
              fzId:obj[j].id,
              fzName:obj[j].jgFzName,
              jjConfig:[]
            })
          }
          break;
        }
      }

    }
  }

}
</script>

<style scoped>
/*    记录参考，不要动哟
[
 {
  jjxId:1,
  jjxName:"A",
  jjxDate:""
 }
 {
  jjxId:2,
  jjxName:"B",
  jjxDate:""
 }
]

{
 1:[
  {
   fzId:1,
   fzName:"AAAAA",
   jjConfig:[
   {
    gsId:1,
    gsName:"XXXXXX",
    jjJe:100000,
    jjxId:1,
    jjxName:"",
    jjxDate:"",
    jkjbj:true
   }
   ]

  },
  {
   fzId:1,
   fzName:"AAAAA",
   gsId:1,
   gsName:"XXXXXX",
   jjJe:100000,
   jjxId:1,
   jjxName:"",
   jjxDate:"",
   jkjbj:false
  }
 ],
 2:[
  {
   fzId:1,
   fzName:"AAAAA",
   gsId:1,
   gsName:"XXXXXX",
   jjJe:100000,
   jjxId:1,
   jjxName:"",
   jjxDate:"",
   jkjbj:false
  },
  {
   fzId:1,
   fzName:"AAAAA",
   gsId:1,
   gsName:"XXXXXX",
   jjJe:100000,
   jjxId:1,
   jjxName:"",
   jjxDate:"",
   jkjbj:false
  }
 ]
}

*/
</style>
